<template>
  <div class="team_page">
    <header class="header">团队管理</header>
    <div class="control">
      <el-button type="primary" size="mini" class="app_add_btn" @click="openAddTeamDialog">添加新的团队</el-button>
      <el-button type="primary" size="mini" class="search_btn" @click="openInviteJoinDialog">加入团队</el-button>
      <el-button type="primary" size="mini" class="search_btn" @click="search">查询团队</el-button>
    </div>
    <div class="container">
      <div class="table_group">
        <el-table :data="teamList" style="" :stripe="true" class="container_table" empty-text="暂无数据">
          <el-table-column prop="id" label="ID" width="40" />
          <el-table-column prop="Name" label="名称" width="100" />
          <el-table-column prop="Remark" label="备注" width="60" />
          <el-table-column prop="UID" label="UID" width="60" />
          <el-table-column prop="AppTypeText" label="应用类型" width="80" />
          <el-table-column prop="createAtText" label="接入时间" width="150" />
          <el-table-column prop="updatedAtText" label="最后更新时间" width="150" />
          <el-table-column prop="statusText" label="状态" width="60" />
          <el-table-column prop="control" label="操作" width="360" >
            <template #default="{row}">
              <el-button ghost @click="openAddTeamDialog(row)">编辑</el-button>
              <el-button ghost @click="delTeam(row)">删除</el-button>
              <el-button ghost @click="openTeamUser(row)">查看用户</el-button>
              <el-button ghost @click="inviteUserInTeam(row)">邀请加入团队</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        v-model:currentPage="pageOptions.pageNum"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[20, 50 ,100]"
        :page-size="pageOptions.limit"
        :pager-count="5"
        :total="pageOptions.total"
        background
        class="page_group"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
      ></el-pagination>
    </div>

    <!-- 添加团队 -->
    <el-dialog
      v-model="isShowAddTeamDialog"
      :title="titleText"
      :width="500"
      @close="closeAddTeamDialog"
      custom-class="add_dialog"
    >
      <div class="main">
        <div class="info_item">
          <div class="label">团队名称</div>
          <el-input class="login_input" v-model="newTeamInfo.Name" placeholder="请输入团队名称" maxLength="16" clearable> </el-input>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeAddTeamDialog">取消</el-button>
          <el-button type="primary" @click="addTeamType == 'add' ? addTeam() : updateTeam()">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看用户 -->
    <el-dialog
      v-model="isShowTeamUserDialog"
      title="已加入的用户"
      :width="900"
      @close="closeTeamUserDialog"
      custom-class="add_dialog"
    >
      <div class="main">
        <el-table :data="userList" style="" :stripe="true" class="container_table" empty-text="暂无数据">
          <el-table-column prop="id" label="ID" width="40" />
          <el-table-column prop="name" label="名称" width="150" />
          <el-table-column prop="account" label="账号" width="120" />
          <el-table-column prop="mobile" label="手机号" width="120" />
          <el-table-column prop="lastIp" label="最后登录IP地址" width="120" />
          <el-table-column prop="createAtText" label="接入时间" width="150" />
          <el-table-column prop="updatedAtText" label="最后更新时间" width="150" />
          <el-table-column prop="statusText" label="状态" width="60" />
          <el-table-column prop="control" label="操作" width="100" >
            <template #default="{row}">
              <el-button ghost @click="delTeamUser(row)">移除团队</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button @click="closeTeamUserDialog">取消</el-button> -->
          <el-button type="primary" @click="closeTeamUserDialog">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 加入团队 -->
    <el-dialog
      v-model="isShowInviteJoinDialog"
      title="加入团队"
      :width="500"
      @close="closeInviteJoinDialog"
      custom-class="add_dialog"
    >
      <div class="main">
        <div class="info_item">
          <div class="label">输入邀请码</div>
          <el-input class="login_input" v-model="inviteCode" placeholder="请输入邀请码" maxLength="32" clearable> </el-input>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeInviteJoinDialog">取消</el-button>
          <el-button type="primary" @click="postInviteUserJoinTeam">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted,ref,getCurrentInstance,nextTick,watchEffect,reactive,Ref, toRefs, watch} from 'vue'
/* API */
import { postTeamInfo, getTeamInfo, getTeamList, updateTeamInfo, delTeamInfo, postUserInTeamCode, postUserInTeam, getTeamUser, delUserOfTeam } from '@/api/team'
/* utils */
import dayjs from 'dayjs';
import qrcode from 'qrcode';
import { browserCopyText } from '@/lib/script/utils';
import { ElMessage, ElMessageBox } from 'element-plus';
export default defineComponent({
  setup(){
    let teamList = ref([]); // 团队列表
    let addTeamType = ref('add'); // 添加/编辑团队弹窗type
    let titleText = ref("添加新的团队"); // 添加/编辑团队弹窗标题
    // 团队信息
    let newTeamInfo = reactive({
      Name: ''
    })
    let isShowAddTeamDialog = ref(false); // 是否显示添加/编辑团队弹窗
    // 分页
    let pageOptions = reactive({
      pageNum: 1,
      limit: 20,
      total: 0,
    })

    let userTeamInfo = null; // 正在查看用户列表的团队信息
    let isShowTeamUserDialog = ref(false); // 是否显示团队用户弹窗
    let userList = ref([]); // 用户列表

    // 加入团队
    let isShowInviteJoinDialog = ref(false); // 是否显示加入团队弹窗
    let inviteCode = ref(''); // 邀请码

    // 处理列表数据(显示)
    const disposeData = data => {
      data = Array.isArray(data) ? data : [];
      return data.map(item => {
        return Object.assign(item, {
          AppTypeText: item.AppType == 1 ? 'web' : '小程序',
          createAtText: dayjs(item.createAt).format('YYYY-MM-DD HH:mm:ss'),
          updatedAtText: dayjs(item.updatedAt).format('YYYY-MM-DD HH:mm:ss'),
          statusText: item.status == 1 ? '正常' : '异常',
        })
      })
    }
    // 打开添加/编辑团队弹窗
    const openAddTeamDialog = teamInfo => {
      console.log('teamInfo', teamInfo);
      if(teamInfo && teamInfo?.id){
        addTeamType.value = 'edit'
        titleText.value = '编辑团队信息'
        newTeamInfo.Name = teamInfo.Name;
        newTeamInfo.id = teamInfo.id;
        console.log('newTeamInfo', newTeamInfo);
      } else {
        addTeamType.value = 'add'
        titleText.value = '添加新的团队'
        newTeamInfo.Name = ''
      }
      isShowAddTeamDialog.value = true;
    }
    // 关闭添加/编辑团队弹窗
    const closeAddTeamDialog = _ => {
      isShowAddTeamDialog.value = false;
    }
    // 添加团队
    const addTeam = _ => {
      let args = newTeamInfo
      postTeamInfo(args).then(resp => {
        let {code, data, message} = resp;
        if(code === 0) {
          ElMessage.success({message: '添加成功'})
          isShowAddTeamDialog.value = false;
          search()
        } else {
          ElMessage.error({message: `code ${code}; ${message}`})
        }
      });
    }
    // 更新团队
    const updateTeam = _ => {
      let args = newTeamInfo
      updateTeamInfo(args).then(resp => {
        let {code, data, message} = resp;
        if(code === 0) {
          ElMessage.success({message: '添加成功'})
          isShowAddTeamDialog.value = false;
          search()
        } else {
          ElMessage.error({message: `code ${code}; ${message}`})
        }
      });
    }
    // 删除团队
    const delTeam = teamInfo => {
      ElMessageBox.confirm('', {
        title: '温馨提示',
        message: '确认删除该团队吗？',
        type: 'warning',
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        callback(action, instance) {
          if(action == 'confirm') {
            delTeamInfo({id: teamInfo.id}).then(resp => {
              let {code, data, message} = resp;
              if(code === 0) {
                ElMessage.success({message: '删除成功'})
                search()
              } else {
                ElMessage.error({message: `code ${code}; ${message}`})
              }
            })
          }
        }
      })
    }
    // 查询团队列表
    const search = () => {
      let args = pageOptions;
      getTeamList(args).then(resp => {
        let {code, data, message} = resp;
        if(code === 0) {
          teamList.value = disposeData(data);
          pageOptions.total = teamList.value.length
        } else {
          ElMessage.error({message: `code ${code}; ${message}`})
        }
      })
    }
    // 打开团队的员工列表
    const openTeamUser = teamInfo => {
      userTeamInfo = teamInfo
      getTeamUserList(teamInfo)
      isShowTeamUserDialog.value = true;
    }
    // 关闭团队的员工列表
    const closeTeamUserDialog = _ => {
      userTeamInfo = null;
      isShowTeamUserDialog.value = false;
    }
    // 获取团队用户列表
    const getTeamUserList = teamInfo => {
      let args = {
        tid: teamInfo.id,
        pageNum: 1,
        limit: 20,
      }
      getTeamUser(args).then(resp => {
        let {code, data, message} = resp;
        if(code === 0) {
          userList.value = disposeData(data);
        } else {
          ElMessage.error({message: `code ${code}; ${message}`})
        }
      })
    }
    // 移除团队的员工
    const delTeamUser = userInfo => {
      ElMessageBox.confirm('', {
        title: '温馨提示',
        message: '确认把该员工从团队中移除吗？',
        type: 'warning',
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        callback(action, instance) {
          if(action == 'confirm') {
            let args = {
              tid: userTeamInfo.id,
              uid: userInfo.id,
            }
            delUserOfTeam(args).then(resp => {
              let {code, data, message} = resp;
              if(code === 0) {
                ElMessage.success({message: '移除成功'})
                getTeamUserList(userTeamInfo)
              } else {
                ElMessage.error({message: `code ${code}; ${message}`})
              }
            })
          }
        }
      })
    }
    // 邀请员工加入团队(生产邀请码)
    const inviteUserInTeam = teamInfo => {
      postUserInTeamCode({tid: teamInfo.id}).then(resp => {
        let {code, data, message} = resp;
        if(code === 0) {
          let flag = browserCopyText(data.invitationCode || '')
          flag && ElMessage.success({message: `邀请码已复制，其他用户可凭此码加入团队`})
        } else {
          ElMessage.error({message: `code ${code}; ${message}`})
        }
      })
    }
    // 打开邀请码加入团队弹窗
    const openInviteJoinDialog = _ => {
      isShowInviteJoinDialog.value = true
    }
    // 关闭邀请码加入团队弹窗
    const closeInviteJoinDialog = _ => {
      isShowInviteJoinDialog.value = false
    }
    // 使用邀请码加入团队
    const postInviteUserJoinTeam = _ => {
      let args = {
        invitationCode: inviteCode.value
      }
      postUserInTeam(args).then(resp => {
        let {code, data, message} = resp;
        if(code === 0) {
          ElMessage.success({message: `加入团队成功！`})
        } else {
          ElMessage.error({message: `code ${code}; ${message}`})
        }
      })
    }
    // 页容量change
    const onSizeChange = val => {
      pageOptions.limit = val;
      pageOptions.pageNum = 1;
      search()
    }
    // 页码change
    const onCurrentChange = val => {
      pageOptions.pageNum = val;
      search()
    }

    search()

    return {
      teamList,
      titleText,
      newTeamInfo,
      addTeamType,
      isShowAddTeamDialog,
      isShowTeamUserDialog,
      userList,
      isShowInviteJoinDialog,
      inviteCode,
      pageOptions,

      openAddTeamDialog,
      closeAddTeamDialog,
      addTeam,
      updateTeam,
      delTeam,
      search,
      openTeamUser,
      closeTeamUserDialog,
      getTeamUser,
      delTeamUser,
      inviteUserInTeam,
      openInviteJoinDialog,
      closeInviteJoinDialog,
      postInviteUserJoinTeam,
      onSizeChange,
      onCurrentChange,
    }
  }
})
</script>

<style lang='less' scoped>
.team_page {
  width: 100%;
  height: 100%;
  overflow: auto;
  position: relative;
  header.header {
    height: 40px;
    line-height: 40px;
    background-color: #fff;
    font-size: 16px;
    padding: 0 16px;
  }
  .control {
    padding: 8px 16px;
  }

  .container {
    width: 100%;
    padding: 0 16px;
    overflow: auto;
    position: absolute;
    left: 0;
    right: 0;
    top: 88px;
    bottom: 0;
    .table_group {
      position: absolute;
      top: 0;
      bottom: 42px;
      left: 16px;
      right: 16px;
      overflow: auto;
    }
    .page_group {
      position: absolute;
      left: 16px;
      bottom: 10px;
    }
  }

  .add_dialog {
    .main {
      .info_item {
        margin-bottom: 10px;
        .label {
          height: 20px;
          margin-bottom: 5px;
        }
      }
    }
  }
}
</style>